package com.my.upload;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 文件上传servlet
 * @author Lelezhang
 * @create 2020-07-15 20:44
 */
public class UploadServlet extends javax.servlet.http.HttpServlet {
    @Override
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        // 判断上传数据是否是多段(只要多段数据才是文件上传的)
        if (ServletFileUpload.isMultipartContent(request)) {
            // 创建工厂实现类FileItemFactory
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            // 创建用于解析上传数据的工具类ServletFileUpload
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            try {
                // 解析上传数据,获取每一个表单项fileItem
                List<FileItem> fileItems = servletFileUpload.parseRequest(request);
                // 遍历
                for (FileItem fileItem : fileItems) {
                    // 判断是否是普通表单类型
                    if (fileItem.isFormField()) {
                        // 普通表单项
                        System.out.println("表单内容name属性值" + fileItem.getFieldName());
                        System.out.println("表单内容value属性值" + fileItem.getString("UTF-8"));
                    } else {
                        // 上传的文件
                        System.out.println("上传文件的name属性值" + fileItem.getFieldName());
                        // 将上传的文件写到某一个位置
                        fileItem.write(new File("D:\\DevelopCode\\File_Upload_Download\\upload\\web" + fileItem.getName()));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

    }
}
